/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ua.yandex.bank;

/**
 *
 * @author vlad
 */
public class Bank {
    
    private final Account[] clients;
    private volatile int clientNumber;
    
    public Bank(int size) {
        this.clientNumber = 0;
        clients = new Account[size];
    }
    
    public void addClient(long balance) {
        clients[clientNumber++] = new Account(balance);
    }
    
    public Account getClient(int pos) {
        return clients[pos];
    }

    public int getClientNumber() {
        return clientNumber;
    }
    
    public void transfer(Account from, Account to, long amount) {
        if (from.getID() != to.getID()) {
            if (from.getID() < to.getID()) {
                synchronized (from) {
                    synchronized (to) {
                        from.withdraw(amount);
                        to.deposit(amount);
                    }
                }
            } else {
                synchronized (to) {
                    synchronized (from) {
                        from.withdraw(amount);
                        to.deposit(amount);
                    }
                }
            }
        }
    }
}
